const fs = require('fs');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const Utils = {};
const SrcPath = path.resolve(__dirname, 'src');
const PageDir = path.resolve(SrcPath, 'pages');

/**
 * 获取入口
 * @return {[type]} [入口配置对象]
 */
Utils.getEntryMap = () => {
  let entryMap = {};
  fs.readdirSync(PageDir).forEach((pathname)=>{
      let fullPathName = path.resolve(PageDir, pathname);
      let stat = fs.statSync(fullPathName);
      let fileName = path.resolve(fullPathName, 'index.js');

      if (stat.isDirectory() && fs.existsSync(fileName)) {
          entryMap[pathname] = fileName;
      }
  });
  return entryMap;
}

/**
 * 获取html模版，并进行配置
 * @param  {[type]} entryMap [入口配置对象]
 * @return {[type]}          [html模版的配置数组]
 */
Utils.getHtmlArray = (entryMap) => {
    let htmlArray = [];
    Object.keys(entryMap).forEach((key)=>{
        let fullPathName = path.resolve(PageDir, key);
        let fileName = path.resolve(fullPathName, key + '.html');

        if (fs.existsSync(fileName)) {
            // html 模版处理
            htmlArray.push(new HtmlWebpackPlugin({
                filename: key + '.html',
                template: fileName,
                chunks: [ 'common', key] // common + 我们的入口
            }));
        }
    });
    return htmlArray;
}

module.exports = {
  Utils
};
